package chapter5_基础构建模块.同步工具类;

import java.util.concurrent.CountDownLatch;

public class CountLatchTest {

    public static void main(String[] args) throws InterruptedException {
        System.out.println("nanoTime:" + timeTasks(5, () -> System.out.println("xxx" + Thread.currentThread().getName())));
    }

    public static long timeTasks(int nThreads, final Runnable task) throws InterruptedException {
        //起始门
        final CountDownLatch startGate = new CountDownLatch(1);
        //结束门
        final CountDownLatch endGate = new CountDownLatch(nThreads);
        for (int i = 0; i < nThreads; i++) {
            Thread t = new Thread(() -> {
                try {
                    // 阻塞等待值为0
                    startGate.await();
                    try {
                        task.run();
                    } finally {
                        endGate.countDown();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
            t.start();
        }
        long start = System.nanoTime();
        startGate.countDown();
        endGate.await();
        long end = System.nanoTime();
        return end - start;
    }
}
